<!doctype html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  
    
      
    

    
  

  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Monda:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|Lobster Two:300,300italic,400,400italic,700,700italic|PT Mono:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="算法," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.0" />






<meta name="description" content="归并算法的基本思想归并排序是建立在归并操作上的一种有效的排序算法。该算法是采用分治法（Divide and Conquer）的一个非常典型的应用。“归并”的含义是将两个或两个以上的有序表组合成一个新的有序表。因此归并排序就是利用归并的思想来实现的，假设初始序列含有n个记录，则可以看成是n个有序的子序列，每个子序列的长度为1，然后两两归并，得到 (n+1)/2个长度为2或1的有序子序列；再两两归并，">
<meta property="og:type" content="article">
<meta property="og:title" content="归并排序">
<meta property="og:url" content="http://yoursite.com/2017/03/09/归并排序/index.html">
<meta property="og:site_name" content="EasyBlog">
<meta property="og:description" content="归并算法的基本思想归并排序是建立在归并操作上的一种有效的排序算法。该算法是采用分治法（Divide and Conquer）的一个非常典型的应用。“归并”的含义是将两个或两个以上的有序表组合成一个新的有序表。因此归并排序就是利用归并的思想来实现的，假设初始序列含有n个记录，则可以看成是n个有序的子序列，每个子序列的长度为1，然后两两归并，得到 (n+1)/2个长度为2或1的有序子序列；再两两归并，">
<meta property="og:updated_time" content="2017-03-10T00:58:42.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="归并排序">
<meta name="twitter:description" content="归并算法的基本思想归并排序是建立在归并操作上的一种有效的排序算法。该算法是采用分治法（Divide and Conquer）的一个非常典型的应用。“归并”的含义是将两个或两个以上的有序表组合成一个新的有序表。因此归并排序就是利用归并的思想来实现的，假设初始序列含有n个记录，则可以看成是n个有序的子序列，每个子序列的长度为1，然后两两归并，得到 (n+1)/2个长度为2或1的有序子序列；再两两归并，">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2017/03/09/归并排序/"/>





  <title> 归并排序 | EasyBlog </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?07a6d49ae67fe991e0ce3c2f3955e0f9";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>










  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">EasyBlog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description"></h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2017/03/09/归并排序/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Gasbylei">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="http://gasbylei.github.io/uploads/avatar.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="EasyBlog">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">
            
            
              
                归并排序
              
            
          </h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-03-09T21:57:52+08:00">
                2017-03-09
              </time>
            

            

            
          </span>

          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2017/03/09/归并排序/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count" data-disqus-identifier="2017/03/09/归并排序/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="归并算法的基本思想"><a href="#归并算法的基本思想" class="headerlink" title="归并算法的基本思想"></a>归并算法的基本思想</h2><p>归并排序是建立在归并操作上的一种有效的排序算法。该算法是采用分治法（Divide and Conquer）的一个非常典型的应用。“归并”的含义是将两个或两个以上的有序表组合成一个新的有序表。因此归并排序就是利用归并的思想来实现的，假设初始序列含有n个记录，则可以看成是n个有序的子序列，每个子序列的长度为1，然后两两归并，得到 (n+1)/2个长度为2或1的有序子序列；再两两归并，….，如此重复，直至得到一个长度为n的有序序列位置，这种排序方法称为2路归并排序。</p>
<a id="more"></a>
<p>归并排序具体算法描述如下(递归版本)：</p>
<ol>
<li>Divide: 把长度为n的输入序列分成两个长度为n/2的子序列。</li>
<li>Conquer: 对这两个子序列分别采用归并排序。</li>
<li>Combine: 将两个排序好的子序列合并成一个最终的排序序列。</li>
</ol>
<h2 id="算法的语言描述："><a href="#算法的语言描述：" class="headerlink" title="算法的语言描述："></a>算法的语言描述：</h2><figure class="highlight c"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="comment">//将两个有序数列a[first...mid]和a[mid...last]合并</span><span class="function"><span class="keyword">void</span> <span class="title">MergeArray</span><span class="params">(<span class="keyword">int</span> a[], <span class="keyword">int</span> first, <span class="keyword">int</span> mid, <span class="keyword">int</span> last, <span class="keyword">int</span> temp[])</span></span>&#123;	<span class="keyword">int</span> i = first, j = mid + <span class="number">1</span>;	<span class="keyword">int</span> m = mid, n = last;	<span class="keyword">int</span> k = <span class="number">0</span>;		<span class="keyword">while</span> ( i &lt;= m &amp;&amp; j &lt;= n )	&#123;	<span class="keyword">if</span> (a[i] &lt;= a[j])		temp[k++] = a[i++];	<span class="keyword">else</span>	temp[k++] = a[j++];	&#125;	<span class="keyword">while</span> (i &lt;= m)	temp[k++] = a[i++];	<span class="keyword">while</span> (j &lt;= n)	temp[k++] = a[j++];	<span class="keyword">for</span> (i = <span class="number">0</span>; i &lt; k; i++)	a[first +<span class="number">1</span>] = temp[i];&#125;</div></pre></td></tr></table></figure>
<pre><code class="c"><span class="comment">//递归地完成归并排序</span>
<span class="function"><span class="keyword">void</span> <span class="title">MergeSort</span><span class="params">(<span class="keyword">int</span> a[], <span class="keyword">int</span> first, <span class="keyword">int</span> last, <span class="keyword">int</span> temp[])</span>
</span>{
<span class="keyword">if</span> (first &lt; last)
{
<span class="keyword">int</span> mid = (first + last) / <span class="number">2</span>;
mergesort(a, first, mid ,temp); <span class="comment">//左边有序</span>
mergesort(a, mid + <span class="number">1</span>, last, temp); <span class="comment">// 右边有序</span>
mergearray(a, first, mid, last, temp); <span class="comment">//再将两个有序数列合并</span>
}
}
</code></pre>
<h2 id="时间复杂度分析："><a href="#时间复杂度分析：" class="headerlink" title="时间复杂度分析："></a>时间复杂度分析：</h2><p>归并排序的效率是比较高的，设数列长为N，将数列分开成小数列一共要logN步，每步都是一个合并有序数列的过程，时间复杂度可以记为O(N)，故一共为O(N*logN)。因为归并排序每次都是在相邻的数据中进行操作，所以归并排序在O(N*logN)的几种排序方法（快速排序，归并排序，希尔排序，堆排序）也是效率比较高的。</p>
<h2 id="列举算法的实际应用："><a href="#列举算法的实际应用：" class="headerlink" title="列举算法的实际应用："></a>列举算法的实际应用：</h2><p>给一个数组，如果该数组的一个子数组，元素之和大于等于给定的一个参数值（lower），小于等于一个给定的参数值（upper），那么这为一组解，求总共有几组解。（leetcode,327题）</p>
<p>解题思路：</p>
<p>首先预处理数组的前缀和，保存到数组 sum 中。然后用归并排序对数组 sum 进行排序，归并排序中有一步调用 merge 函数，将有序的左数组和右数组进行合并，而这时的右数组中的任一元素在 sum 数组中的位置正是在左数组任一元素之后！利用这，我们可以在 merge 前，对 left 数组和 right 数组满足条件的元素进行求解。</p>
<pre><code class="js"><span class="comment">//返回 b[j] - a[i] 值在 [wlower, wupper] 范围内组数</span>
<span class="function"><span class="keyword">function</span> <span class="title">getAns</span>(<span class="params">a, b</span>) </span>{
  <span class="keyword">var</span> sum = <span class="number">0</span>;
  <span class="keyword">var</span> lena = a.length; 
  <span class="keyword">var</span> lenb = b.length;
  <span class="keyword">var</span> start = <span class="number">0</span>;
  <span class="keyword">var</span> end = <span class="number">0</span>;

  <span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>; i &lt; lenb; i++) {
    <span class="comment">// to get start</span>
    <span class="keyword">while</span> (b[i] - a[start] &gt;= wlower) {
      start++;
    }
    <span class="comment">// to get end</span>
    <span class="keyword">while</span> (b[i] - a[end] &gt; wupper) {
      end++;
    }
    sum += start - end;
  }
  <span class="keyword">return</span> sum;
  }
</code></pre>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>


    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/算法/" rel="tag"># 算法</a>
          
        </div>
      

      
        
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/03/06/在mac上如何使用docker安装oracle-11g/" rel="next" title="在mac上如何使用docker安装oracle 11g?">
                <i class="fa fa-chevron-left"></i> 在mac上如何使用docker安装oracle 11g?
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/03/13/学习CSS布局(一)/" rel="prev" title="学习CSS布局(一)">
                学习CSS布局(一) <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>

          
          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="disqus_thread">
        <noscript>
          Please enable JavaScript to view the
          <a href="//disqus.com/?ref_noscript">comments powered by Disqus.</a>
        </noscript>
      </div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="http://gasbylei.github.io/uploads/avatar.png"
               alt="Gasbylei" />
          <p class="site-author-name" itemprop="name">Gasbylei</p>
           
              <p class="site-description motion-element" itemprop="description"></p>
           
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives">
                <span class="site-state-item-count">17</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">6</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/Gasbylei" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#归并算法的基本思想"><span class="nav-number">1.</span> <span class="nav-text">归并算法的基本思想</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#算法的语言描述："><span class="nav-number">2.</span> <span class="nav-text">算法的语言描述：</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#时间复杂度分析："><span class="nav-number">3.</span> <span class="nav-text">时间复杂度分析：</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#列举算法的实际应用："><span class="nav-number">4.</span> <span class="nav-text">列举算法的实际应用：</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy;  2015 - 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Gasbylei</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    
    
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  



  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>

  
  <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>



  



  

    <script type="text/javascript">
      var disqus_shortname = 'gatsbylei';
      var disqus_identifier = '2017/03/09/归并排序/';

      var disqus_title = "归并排序";


      function run_disqus_script(disqus_script) {
        var dsq = document.createElement('script');
        dsq.type = 'text/javascript';
        dsq.async = true;
        dsq.src = '//' + disqus_shortname + '.disqus.com/' + disqus_script;
        (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
      }

      run_disqus_script('count.js');

      
        var disqus_config = function () {
            this.page.url = disqus_url;
            this.page.identifier = disqus_identifier;
            this.page.title = disqus_title;
        };
        run_disqus_script('embed.js');
      

    </script>
  










  
  

  

  

  

  


  

</body>
</html>
